/**
 * 属性状态管理模块
 * 管理角色属性数据和实时计算
 */

import attributeCalculator from '@/utils/attributeCalculator'
import { getAttributes, distributeAttributes, distributeAffinityPoints } from '@/api/character'

const state = {
  // 基础加点属性
  baseAttributes: {
    constitution: 0,
    strength: 0,
    agility: 0
  },
  
  // 相性加点属性
  affinityAttributes: {
    attack: 0,
    defense: 0,
    illusion: 0
  },
  
  // 可分配相性点
  availableAffinityPoints: 0,
  
  // 计算后的基础属性
  basicStats: {
    health: 0,
    defense: 0,
    baseDamage: 0,
    speed: 0
  },
  
  // 进阶属性
  advancedStats: {
    damageIncrease: 0,
    damageReduction: 0,
    critRate: 0,
    abnormalResist: 0,
    controlSuccess: 0,
    dodgeRate: 0,
    hitRate: 0
  },
  
  // 装备加成
  equipmentBonus: {
    health: 0,
    defense: 0,
    baseDamage: 0,
    speed: 0,
    damageIncrease: 0,
    damageReduction: 0,
    critRate: 0,
    abnormalResist: 0,
    controlSuccess: 0,
    dodgeRate: 0,
    hitRate: 0
  },
  
  // 技能加成
  skillBonus: {
    health: 0,
    defense: 0,
    baseDamage: 0,
    speed: 0,
    damageIncrease: 0,
    damageReduction: 0,
    critRate: 0,
    abnormalResist: 0,
    controlSuccess: 0,
    dodgeRate: 0,
    hitRate: 0
  },
  
  // 其他信息
  availablePoints: 0,
  combatPower: 0,
  
  // 已装备的装备列表（从属性接口返回）
  equippedItems: {
    weapon: null,      // 武器 (type=1)
    helmet: null,      // 头盔 (type=3)
    armor: null,       // 衣服 (type=2)
    boots: null        // 鞋子 (type=4)
  },
  
  // 套装名称（如果有套装）
  setName: null,
  
  // 临时分配的属性点（用于预览）
  tempDistribution: {
    constitution: 0,
    strength: 0,
    agility: 0
  },
  
  // 临时分配的相性点（用于预览）
  tempAffinityDistribution: {
    attack: 0,
    defense: 0,
    illusion: 0
  },
  
  // 预览数据
  previewData: null,
  
  // 加载状态
  loading: false,
  error: null
}

const mutations = {
  // 设置基础属性
  SET_BASE_ATTRIBUTES(state, attributes) {
    state.baseAttributes = { ...state.baseAttributes, ...attributes }
  },
  
  // 设置基础统计数据
  SET_BASIC_STATS(state, stats) {
    state.basicStats = { ...state.basicStats, ...stats }
  },
  
  // 设置进阶统计数据
  SET_ADVANCED_STATS(state, stats) {
    state.advancedStats = { ...state.advancedStats, ...stats }
  },
  
  // 设置装备加成
  SET_EQUIPMENT_BONUS(state, bonus) {
    state.equipmentBonus = { ...state.equipmentBonus, ...bonus }
  },
  
  // 设置技能加成
  SET_SKILL_BONUS(state, bonus) {
    state.skillBonus = { ...state.skillBonus, ...bonus }
  },
  
  // 设置可分配点数
  SET_AVAILABLE_POINTS(state, points) {
    state.availablePoints = points
  },
  
  // 设置战斗力
  SET_COMBAT_POWER(state, power) {
    state.combatPower = power
  },
  
  // 设置临时分配
  SET_TEMP_DISTRIBUTION(state, distribution) {
    state.tempDistribution = { ...state.tempDistribution, ...distribution }
  },
  
  // 重置临时分配
  RESET_TEMP_DISTRIBUTION(state) {
    state.tempDistribution = {
      constitution: 0,
      strength: 0,
      agility: 0
    }
  },
  
  // 设置相性属性
  SET_AFFINITY_ATTRIBUTES(state, attributes) {
    state.affinityAttributes = { ...state.affinityAttributes, ...attributes }
  },
  
  // 设置可分配相性点
  SET_AVAILABLE_AFFINITY_POINTS(state, points) {
    state.availableAffinityPoints = points
  },
  
  // 设置临时相性分配
  SET_TEMP_AFFINITY_DISTRIBUTION(state, distribution) {
    state.tempAffinityDistribution = { ...state.tempAffinityDistribution, ...distribution }
  },
  
  // 重置临时相性分配
  RESET_TEMP_AFFINITY_DISTRIBUTION(state) {
    state.tempAffinityDistribution = {
      attack: 0,
      defense: 0,
      illusion: 0
    }
  },
  
  // 设置预览数据
  SET_PREVIEW_DATA(state, data) {
    state.previewData = data
  },
  
  // 清除预览数据
  CLEAR_PREVIEW_DATA(state) {
    state.previewData = null
  },
  
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  },
  
  // 设置错误信息
  SET_ERROR(state, error) {
    state.error = error
  },
  
  // 清除错误信息
  CLEAR_ERROR(state) {
    state.error = null
  },
  
  // 设置已装备物品
  SET_EQUIPPED_ITEMS(state, { items, setName }) {
    // 装备类型映射: 1=武器, 2=衣服, 3=头盔, 4=鞋子
    const slotMap = {
      1: 'weapon',
      2: 'armor',
      3: 'helmet',
      4: 'boots'
    }
    
    // 重置所有槽位
    state.equippedItems = {
      weapon: null,
      helmet: null,
      armor: null,
      boots: null
    }
    
    // 根据装备类型填充槽位
    if (Array.isArray(items)) {
      items.forEach(item => {
        const slot = slotMap[item.type]
        if (slot && item.is_up) {
          state.equippedItems[slot] = {
            id: item.id,
            equipmentId: item.id,
            name: item.name,
            type: item.type,
            level: item.level,
            remodelLevel: item.remodel_level,
            isTz: item.is_tz || false
          }
        }
      })
    }
    
    // 设置套装名称
    state.setName = setName || null
  }
}

const actions = {
  /**
   * 加载属性数据（简化版本）
   */
  async loadAttributesSimple({ commit }, roleId) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await getAttributes({ roleId })
      
      if (response && response.data) {
        const data = response.data.attributes
        const equipmentList = response.data.equipmentList || {}
        
        commit('SET_BASE_ATTRIBUTES', {
          constitution: data.constitution || 0,
          strength: data.strength || 0,
          agility: data.agility || 0
        })
        
        commit('SET_BASIC_STATS', {
          health: data.health || 0,
          defense: data.defense || 0,
          baseDamage: data.baseDamage || 0,
          speed: data.speed || 0
        })
        
        commit('SET_ADVANCED_STATS', {
          damageIncrease: data.damageIncrease || 0,
          damageReduction: data.damageReduction || 0,
          critRate: data.critRate || 0,
          abnormalResist: data.abnormalResist || 0,
          controlSuccess: data.controlSuccess || 0,
          dodgeRate: data.dodgeRate || 0,
          hitRate: data.hitRate || 0
        })
        
        commit('SET_AVAILABLE_POINTS', data.availablePoints || 0)
        commit('SET_COMBAT_POWER', data.combatPower || 0)
        
        // 处理装备列表
        if (equipmentList.equip_list) {
          commit('SET_EQUIPPED_ITEMS', {
            items: equipmentList.equip_list,
            setName: equipmentList.tz_name
          })
        }
        
        return response.data
      } else {
        throw new Error(response?.msg || '加载属性数据失败')
      }
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },

  /**
   * 加载属性数据
   */
  async loadAttributes({ commit }, roleId) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await getAttributes({ roleId })
      
      if (response && response.data) {
        const data = response.data.attributes
        
        if (data.constitution) {
          commit('SET_BASE_ATTRIBUTES', {
            constitution: data.constitution.total || 0,
            strength: data.strength.total || 0,
            agility: data.agility.total || 0
          })
        }
        
        commit('SET_BASIC_STATS', {
          health: data.health?.total || 0,
          defense: data.defense?.total || 0,
          baseDamage: data.baseDamage?.total || 0,
          speed: data.speed?.total || 0
        })
        
        commit('SET_ADVANCED_STATS', {
          damageIncrease: data.damageIncrease?.total || 0,
          damageReduction: data.damageReduction?.total || 0,
          critRate: data.critRate?.total || 0,
          abnormalResist: data.abnormalResist?.total || 0,
          controlSuccess: data.controlSuccess?.total || 0,
          dodgeRate: data.dodgeRate?.total || 0,
          hitRate: data.hitRate?.total || 0
        })
        
        commit('SET_AVAILABLE_POINTS', data.availablePoints || 0)
        commit('SET_COMBAT_POWER', data.combatPower || 0)
        
        return response.data
      } else {
        throw new Error(response?.msg || '加载属性数据失败')
      }
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 分配属性点
   */
  async distributeAttributePoints({ commit, state, dispatch }, { roleId, distribution }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await distributeAttributes({
        roleId,
        constitution: distribution.constitution || 0,
        strength: distribution.strength || 0,
        agility: distribution.agility || 0
      })
      
      if (response && response.code === 1) {
        commit('RESET_TEMP_DISTRIBUTION')
        commit('CLEAR_PREVIEW_DATA')
        
        await dispatch('loadAttributes', roleId)
        
        return response
      } else {
        throw new Error(response?.msg || '属性分配失败')
      }
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 预览属性变化
   */
  async previewAttributeChanges({ commit, state }, { roleId, changes }) {
    try {
      // 使用本地计算器进行实时预览
      const currentAttrs = {
        constitution: state.baseAttributes.constitution,
        strength: state.baseAttributes.strength,
        agility: state.baseAttributes.agility
      }
      
      const bonus = {
        equipment: state.equipmentBonus,
        skill: state.skillBonus
      }
      
      const previewData = attributeCalculator.previewAttributeChanges(
        currentAttrs,
        changes,
        bonus
      )
      
      commit('SET_PREVIEW_DATA', previewData)
      
      return previewData
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    }
  },
  
  /**
   * 分配相性点
   * @param {Object} param0 - Vuex上下文
   * @param {Object} payload - 包含roleId和相性点分配数据
   */
  async distributeAffinityPoints({ commit, dispatch }, { roleId, affinityPoints }) {
    try {
      commit('SET_LOADING', true)
      commit('CLEAR_ERROR')
      
      const response = await distributeAffinityPoints({
        role_id: roleId,
        attack: affinityPoints.attack || 0,
        defense: affinityPoints.defense || 0,
        illusion: affinityPoints.illusion || 0
      })
      
      if (response && response.code === 1) {
        // 重新加载属性数据以获取最新状态
        await dispatch('loadAttributesSimple', roleId)
        return response.data
      } else {
        throw new Error(response?.msg || '分配相性点失败')
      }
    } catch (error) {
      commit('SET_ERROR', error.message)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  /**
   * 调整临时分配
   */
  adjustTempDistribution({ commit, dispatch, state }, { attribute, change }) {
    const newDistribution = { ...state.tempDistribution }
    const currentValue = newDistribution[attribute] || 0
    const newValue = Math.max(0, currentValue + change)
    
    // 检查是否有足够的可分配点数
    const totalUsed = Object.values(newDistribution).reduce((sum, val) => sum + val, 0)
    const remainingPoints = state.availablePoints - totalUsed
    
    if (change > 0 && remainingPoints <= 0) {
      throw new Error('可分配点数不足')
    }
    
    newDistribution[attribute] = newValue
    commit('SET_TEMP_DISTRIBUTION', newDistribution)
    
    // 实时预览属性变化
    dispatch('previewAttributeChanges', {
      roleId: uni.getStorageSync('role_id'),
      changes: newDistribution
    })
  },
  
  /**
   * 重置临时分配
   */
  resetTempDistribution({ commit }) {
    commit('RESET_TEMP_DISTRIBUTION')
    commit('CLEAR_PREVIEW_DATA')
  },
  
  /**
   * 更新装备加成
   */
  updateEquipmentBonus({ commit, dispatch, state }, bonus) {
    commit('SET_EQUIPMENT_BONUS', bonus)
    
    // 重新计算所有属性
    dispatch('recalculateAttributes')
  },
  
  /**
   * 更新技能加成
   */
  updateSkillBonus({ commit, dispatch, state }, bonus) {
    commit('SET_SKILL_BONUS', bonus)
    
    // 重新计算所有属性
    dispatch('recalculateAttributes')
  },
  
  /**
   * 重新计算所有属性
   */
  recalculateAttributes({ commit, state }) {
    const bonus = {
      equipment: state.equipmentBonus,
      skill: state.skillBonus
    }
    
    const calculatedAttrs = attributeCalculator.calculateAllAttributes(
      state.baseAttributes,
      bonus
    )
    
    // 更新计算后的属性
    commit('SET_BASIC_STATS', {
      health: calculatedAttrs.health,
      defense: calculatedAttrs.defense,
      baseDamage: calculatedAttrs.baseDamage,
      speed: calculatedAttrs.speed
    })
    
    commit('SET_ADVANCED_STATS', {
      damageIncrease: calculatedAttrs.damageIncrease,
      damageReduction: calculatedAttrs.damageReduction,
      critRate: calculatedAttrs.critRate,
      abnormalResist: calculatedAttrs.abnormalResist,
      controlSuccess: calculatedAttrs.controlSuccess,
      dodgeRate: calculatedAttrs.dodgeRate,
      hitRate: calculatedAttrs.hitRate
    })
    
    commit('SET_COMBAT_POWER', calculatedAttrs.combatPower)
  }
}

const getters = {
  // 获取当前属性（包括预览）
  currentAttributes: (state) => {
    if (state.previewData) {
      return state.previewData
    }
    
    return {
      ...state.baseAttributes,
      ...state.basicStats,
      ...state.advancedStats,
      combatPower: state.combatPower
    }
  },
  
  // 获取剩余可分配点数
  remainingPoints: (state) => {
    const usedPoints = Object.values(state.tempDistribution).reduce((sum, val) => sum + val, 0)
    return state.availablePoints - usedPoints
  },
  
  // 是否有临时分配
  hasTempDistribution: (state) => {
    return Object.values(state.tempDistribution).some(val => val > 0)
  },
  
  // 获取属性增量信息
  attributeIncrements: () => (attrType) => {
    return attributeCalculator.getAttributeIncrement(attrType)
  },
  
  // 格式化属性显示
  formatAttribute: () => (value, type) => {
    return attributeCalculator.formatAttributeDisplay(value, type)
  },
  
  // 获取指定槽位的装备
  getEquippedItem: (state) => (slot) => {
    return state.equippedItems[slot] || null
  },
  
  // 获取套装名称
  getSetName: (state) => {
    return state.setName
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}